import time

import jsonpickle
import search.function
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import render

from .models import AccountUser, CommentsQuestion, Question, ReplyQuestion

# Create your views here.


def group(request):
    user = request.session.get('login', None)
    groupname = ';%s;' % request.GET.get('gname', 'world')
    msg, errormsg = search.function.get_msg(request)
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        user.group = user.group.split('@')
        for count, each in enumerate(user.group):
            user.group[count] = each[1:-1]
        user.group.append('world')
        user.group = user.group[::-1]
    if groupname != ';world;' and (not user or not groupname[1:-1] in user.group):
        return HttpResponseRedirect('/community/group/?ecode=-5')
    questions = Question.objects.filter(group__contains=groupname)
    ques = []
    if questions.exists():
        for eachquestion in questions:
            temp = eachquestion.__dict__
            try:
                temp['user'] = eachquestion.user
            except:
                temp['user'] = "用户已注销"
            coms = CommentsQuestion.objects.filter(position=eachquestion)
            temp['comnum'] = 0
            if coms.exists():
                temp['lastreply'] = coms.last()
                for com in coms:
                    replys = ReplyQuestion.objects.filter(position=com)
                    temp['comnum'] += 1 + replys.count()
                    if replys.exists():
                        for reply in replys:
                            if reply.time > temp['lastreply'].time:
                                temp['lastreply'] = reply
            else:
                temp['lastreply'] = CommentsQuestion(time=eachquestion.time)
            ques.append(temp)
    ques.sort(key=lambda question: question['lastreply'].time, reverse=True)
    if groupname == ';world;':
        groupUser = AccountUser.objects.all()
    else:
        groupUser = AccountUser.objects.filter(group__contains=groupname)
    groupname = groupname[1:-1]
    questions = ques
    return render(request, 'community_group.html', locals())
    # return render(request, 'community_group.html', {'user':user, 'groupUser':groupUser, 'groupname':groupname[1:-1], 'questions':ques})


def new_question(request):
    user = request.session.get('login', None)
    groupname = ';%s;' % request.GET.get('gname', 'world')
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
    else:
        return HttpResponseRedirect('/login?url=/community/newquestion/?gname=%s' % groupname)
    user.group = user.group.split('@')
    for count, each in enumerate(user.group):
        user.group[count] = each[1:-1]
    user.group.append('world')
    user.group = user.group[::-1]
    if request.method == "POST":
        qtitle = request.POST.get('qtitle', None)
        qtext = request.POST.get('qtext', None)
        qtag = request.POST.get('qtags', None)
        if qtitle and qtext:
            if qtag:
                qtag = ';%s;' % qtag
            try:
                if Question.objects.filter(title=qtitle, user=user, group=groupname).exists():
                    errormsg = '您已发布过相同的问题'
                else:
                    newQ = Question(title=qtitle, content=qtext, user=user, tags=qtag,
                                    group=groupname, time=search.function.time_to_datetime(time.time()))
                    newQ.save()
                Q = Question.objects.get(
                    title=qtitle, user=user, group=groupname)
            except Exception as e:
                return HttpResponse('Sorry! Error:%s' % e)
            return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (Q.id, groupname[1:-1]))
    groupname = groupname[1:-1]
    return render(request, 'newquestion.html', locals())


def question(request):
    user = request.session.get('login', None)
    qid = request.GET.get('q', None)
    errormsg = None
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)

    if qid:
        try:
            thequestion = Question.objects.get(id=qid)
            grouplist = thequestion.group.split('@')
            if not ';world;' in grouplist and thequestion.canlink != 1:
                if user:
                    grouplist = grouplist + user.group.split('@')
                    if len(grouplist) == len(set(grouplist)):
                        return HttpResponseRedirect('/community/group/?ecode=-6')
                else:
                    return HttpResponseRedirect('/community/group/?ecode=-6')
        except:
            errormsg = "读取编号为#%s的问题失败" % qid
            url = '/community/group'
            return render(request, '404.html', {'errormsg': errormsg})
        if request.method == "POST":
            ctext = request.POST.get('ctext', None)
            rtext = request.POST.get('rtext', None)
            if ctext:
                try:
                    if CommentsQuestion.objects.filter(user=user, content=ctext, position=thequestion).exists():
                        errormsg = "不要回复相同内容"
                    else:
                        newC = CommentsQuestion(
                            user=user, position=thequestion, content=ctext, time=search.function.time_to_datetime(time.time()))
                        newC.save()
                        search.function.reply_notification(newC)
                except Exception as e:
                    errormsg = "在问题#%s中回复失败：%s" % (thequestion.id, e)
                if errormsg:
                    return render(request, '404.html', {'errormsg': errormsg})
            else:
                if rtext:
                    cpositon = request.GET.get('p', None)
                    gname = request.GET.get('gname', "world")
                    try:
                        cp = CommentsQuestion.objects.get(id=int(cpositon))
                    except Exception as e:
                        errormsg = "Quick reply faile:%s" % e
                        return render(request, '404.html', {'errormsg': errormsg})
                    if cpositon and not ReplyQuestion.objects.filter(user=user, content=rtext, position=cp).exists():
                        newR = ReplyQuestion(
                            user=user, position=cp, content=rtext, time=search.function.time_to_datetime(time.time()))
                        newR.save()
                        search.function.reply_notification(newR)
                    return HttpResponseRedirect("/community/question/?q=%s&gname=%s" % (qid, gname))
        comments = CommentsQuestion.objects.filter(position=thequestion)
        thequestion.tags = thequestion.tags[1:-1]
        coms = []
        try:
            for count, each in enumerate(comments):
                replys = ReplyQuestion.objects.filter(position=each)
                temp = each.__dict__
                temp['replys'] = replys
                temp['user'] = each.user
                coms.append(temp)
        except Exception as e:
            print(e)
        return render(request, 'question.html', {'user': user, 'question': thequestion, 'coms': coms})
    else:
        return HttpResponseRedirect('/community/group')


def delete(request):
    user = request.session.get('login', None)
    t = request.GET.get('t', None)
    q = request.GET.get('q', None)
    deleteid = request.GET.get('id', None)
    gname = request.GET.get('gname', "world")
    errormsg = None
    switch_DB = {'q': Question, 'c': CommentsQuestion, 'qr': ReplyQuestion}
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
    if t in switch_DB.keys() and deleteid:
        try:
            deleteitem = switch_DB[t].objects.get(id=deleteid)
        except Exception as e:
            print(e)
            return HttpResponseRedirect("/community/question/?q=%s&gname=%s" % (q, gname))
        if deleteitem.user == user:
            deleteitem.delete()
        else:
            errormsg = "你不能删除别人的信息"
        if t == 'q':
            return HttpResponseRedirect("/community/group/?gname=%s" % gname)
    return HttpResponseRedirect("/community/question/?q=%s&gname=%s" % (q, gname))


def edit_question(request):
    user = request.session.get('login', None)
    qid = request.GET.get('id', None)
    gname = request.GET.get('gname', "world")
    errormsg = None
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if qid:
            thequesiton = Question.objects.filter(id=int(qid))
            if thequesiton.exists() and thequesiton.first().user == user:
                if request.method == "POST":
                    qtitle = request.POST.get('qtitle', None)
                    qtext = request.POST.get('qtext', None)
                    qtag = request.POST.get('qtags', None)
                    if qtitle and qtext:
                        if qtag:
                            qtag = ';%s;' % qtag
                        try:
                            qtext = qtext + \
                                '\n\n *重新编辑于：%s*' % time.strftime(
                                    "%Y-%m-%d %H:%M:%S", time.localtime())
                            thequesiton.update(
                                title=qtitle, content=qtext, tags=qtag)
                        except Exception as e:
                            return HttpResponse('Sorry! Error:%s' % e)
                        return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (thequesiton.first().id, gname))
                else:
                    canlink = request.GET.get('canlink', None)
                    status = request.GET.get('status', None)
                    if canlink or status:
                        try:
                            thequesiton.update(canlink=int(canlink))
                        except:
                            thequesiton.update(status=int(status))
                        return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
                    return render(request, 'editquestion.html', {'question': thequesiton.first(), 'user': user, 'title': 'edit question'})
            else:
                errormsg = "您不能编辑其他人发布的问题"
                return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
        else:
            return HttpResponse('请求中缺少必要参数：id')
    return HttpResponseRedirect('/login?ecode=-1&url=%s' % request.get_full_path())


def edit_question_comment(request):
    user = request.session.get('login', None)
    qid = request.GET.get('qid', None)
    cid = request.GET.get('cid', None)
    gname = request.GET.get('gname', "world")
    errormsg = None
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if qid and cid:
            thequestion = Question.objects.filter(id=int(qid))
            thecomment = CommentsQuestion.objects.filter(id=int(cid))
            if thecomment.exists() and thecomment.first().user == user and thecomment.first().position == thequestion.first():
                if request.method == "POST":
                    qtext = request.POST.get('qtext', None)
                    if qtext:
                        try:
                            qtext = qtext + \
                                '\n\n *重新编辑于：%s*' % time.strftime(
                                    "%Y-%m-%d %H:%M:%S", time.localtime())
                            thecomment.update(content=qtext)
                        except Exception as e:
                            return HttpResponse('Sorry! Error:%s' % e)
                        return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (thequestion.first().id, gname))
                else:
                    return render(request, 'editquestioncomment.html', {'com': thecomment.first(), 'user': user, 'title': 'edit comment'})
            else:
                errormsg = "您不能编辑其他人发布的评论"
                return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
        else:
            return HttpResponse('请求中缺少必要参数：id')
    return HttpResponseRedirect('/login?ecode=-1&url=%s' % request.get_full_path())


def group_add(request):
    user = request.session.get('login', None)
    qid = request.GET.get('id', None)
    gname = request.GET.get('gname', "world")
    tgname = request.GET.get('tgname', None)
    errormsg = None
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        print(';%s;' % tgname in user.group, tgname, user.group)
        if qid and tgname and ';%s;' % tgname in user.group:
            question = Question.objects.filter(id=int(qid))
            if question.exists():
                if ';%s;' % tgname in question.first().group:
                    return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
                else:
                    question.update(
                        group=question.first().group+'@;%s;' % tgname)
                    return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
    return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))


def group_remove(request):
    user = request.session.get('login', None)
    qid = request.GET.get('id', None)
    gname = request.GET.get('gname', "world")
    tgname = request.GET.get('tgname', None)
    errormsg = None
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if qid and tgname and ';%s;' % tgname in user.group:
            question = Question.objects.filter(id=int(qid))
            if question.exists():
                if ';%s;' % tgname not in question.first().group:
                    return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
                else:
                    if question.first().group.find(';%s;' % tgname) > 1:
                        question.update(group=question.first().group[:question.first().group.find(
                            ';%s;' % tgname)-1]+question.first().group[question.first().group.find(';%s;' % tgname)+len(';%s;' % tgname):])
                    else:
                        try:
                            question.update(group=question.first().group[question.first(
                            ).group.find(';%s;' % tgname)+len(';%s;' % tgname)+1:])
                        except:
                            pass
                    return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
    return HttpResponseRedirect('/community/question/?q=%s&gname=%s' % (qid, gname))
